package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

@RestController
@RequestMapping("/admin/report")
@Slf4j
@Api(tags = "统计报表相关接口")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private WorkspaceService workspaceService;

    @GetMapping("/turnoverStatistics")
    @ApiOperation("营业额数据统计")
    public Result turnoverStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        TurnoverReportVO vo = reportService.getTurnover(begin, end);
        return Result.success();
    }

    @GetMapping("/userStatistics")
    @ApiOperation("用户数据统计")
    public Result userStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        UserReportVO vo = reportService.getUserStatistics(begin, end);
        return Result.success(vo);
    }

    @GetMapping("/ordersStatistics")
    @ApiOperation("订单数据统计")
    public Result ordersStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        OrderReportVO vo = reportService.getOrdersStatistics(begin, end);
        return Result.success(vo);
    }

    @GetMapping("/top10")
    @ApiOperation("商品销量排行榜前十")
    public Result top10(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        SalesTop10ReportVO vo = reportService.getTop10(begin, end);
        return Result.success(vo);
    }

    /**
     * 导出运营数据
     * @param response
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        XSSFWorkbook export = workspaceService.export();

        // 输出表格
        try {
            export.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
